
import * as React from 'react';
import { Breadcrumb, Box, Typography, Form, Checkbox, Radio, Input, Field } from '@alifd/next';
import styles from './index.module.scss';
import dahai, { Project } from 'common_library/dahai';
import ChangjingTable from './ChangjingTable';

export interface FormCreaterProps {
    config: Array<any>;
    data: object;
    orgName: string
    project: string
    filename: string
}


export default class FormCreater extends React.Component<FormCreaterProps> {
    project: Project
    field
    constructor(props: FormCreaterProps) {
        super(props);
        this.field = new Field(this, {
            values: (props.data || {})
        });
        this.project = dahai.createProject(props.orgName, props.project);
        this.state.data = this.props.data || {};
    }
    createInputHtml(key, value) {
        let props: any = {};
        if (value) {
            props.id = "current_to_submit";
            // props.autoFocus = true;
        }
        return <Input defaultValue={value} name={key} {...props}>
        </Input>
    }
    createChangjingHtml(key, value, configValue) {
        let fidldProps = this.field.init(key);
        return <ChangjingTable key={key} title={configValue.title} flow={configValue.flow} dataSource={fidldProps.value} onChange={(value) => {
            fidldProps.onChange(value);
        }}></ChangjingTable>
    }

    createTextareaHtml(key, value, configValue) {
        if ((configValue && configValue.defaultValue) && !value) {
            value = configValue.defaultValue;
        }
        let props: any = {};
        if (value) {
            props.id = "current_to_submit";
            // props.autoFocus = true;
        }
        return <Input.TextArea className={styles.textareaInput} autoHeight={{
            minRows: 1,
            maxRows: 10
        }} {...props} {...this.field.init(key)}>
        </Input.TextArea>
    }
    createRadioHtml(pKey, value, configValue?) {
        let elems = configValue.map(({ key, text }) => {
            return {
                value: key,
                label: text,
            };
        });
        console.log(value, configValue);
        let mapProps = this.field.init(pKey);
        if (!mapProps.value && configValue.length > 0) {
            this.field.setValue(pKey, '1');
        }
        return <Form.Item className={styles.formItem}>
            <Radio.Group
                dataSource={elems}
                {...mapProps}
                onChange={(...args) => {
                    mapProps.onChange(...args);
                    this.radioChange(...args);
                }}
            />
        </Form.Item>;
    }
    createCheckboxHtml(pKey, value, configValue?) {
        let elems = configValue.map(({ key, text, link }) => {
            const isChecked = value.find(item => {
                if (item.key == key) {
                    return item.value;
                }
            });
            return <Checkbox checked={isChecked} value={key} name={pKey}>
                <a href={`/${link}/${key}`} target="_blank">{text}</a>
            </Checkbox>
        });
        return <Checkbox.Group>
            {elems}
        </Checkbox.Group>
    }
    createShowHtml(type, key, value, configValue?) {
        let inputHtml = this.createInputHtml(key, value);
        if (type == 'textarea') {
            inputHtml = this.createTextareaHtml(key, value, configValue);
        } else if (type == 'radio') {
            inputHtml = this.createRadioHtml(key, value, configValue);
        } else if (type == 'checkbox') {
            inputHtml = this.createCheckboxHtml(key, value, configValue);
        } else if (type == 'changjing') {
            inputHtml = this.createChangjingHtml(key, value, configValue);
        }
        return inputHtml;
    }
    /**
     * 
     * @param configs 配置
     * @param saveData 已经填写的数据
     * @param defaults 可能是头部的一些提示啥的
     * @param parentKey 第一个，或者上一个key
     * @param parentFlowKey 流程控制的父key
     * @returns 
     */
    printConfig(configs, saveData, defaults, parentKey, parentFlowKey?) {
        let results: any[] = [];
        let flowData = {
            return: false,
            continue: false
        };
        if (!configs) {
            return {
                listData: [],
                flowData
            };
        }
        for (var i = 0; i < configs.length; i++) {
            // 看看上一个是什么
            const config = configs[i];
            const key = (parentKey && parentKey.trim() != '') ? (parentKey + '_' + config.key) : config.key;
            if (!saveData[key] && config.defaultValue) {
                if (parentFlowKey) {
                    if (config.defaultValue[parentFlowKey]) {
                        saveData[key] = config.defaultValue[parentFlowKey].trim();
                        this.field.setValue(key, saveData[key]);
                    }
                } else {
                    saveData[key] = config.defaultValue.trim();
                    this.field.setValue(key, saveData[key]);
                }
            }
            const createFunc = config.print ? config.print : (data) => {
                return data;
            };
            const title = config.title;
            const tip = config.tip || config.title;
            if (config.type == 'flow') {
                if (!config.flowType || (config.flowType && config.flowType == 'return')) {
                    flowData.return = config.value;
                } else if (config.flowType && config.flowType == 'continue') {
                    flowData.continue = config.value;
                }
            } else if (config.type == 'checkResult' || config.type == 'checkPlan') {
                // const configValue = config.configValue;
                // const checkResult = [];
                // let isChecked = true;
                // const datadir = config.type == 'checkResult' ? 'results' : 'plans';
                // const link = config.type == 'checkResult' ? 'result' : 'plan';
                // // 列出来
                // for (let c = 0; c < configValue.length; c++) {
                //     // 获取数据，看看最后一个有没有填写
                //     let tempKey = configValue[c];
                //     const data = await this.getSaveData(tempKey, datadir);
                //     const endKey = 'fashi_' + this.getTodayDateStr();
                //     if (data[endKey] && data[endKey].trim() != '') {
                //         checkResult.push({
                //             key: tempKey,
                //             value: true
                //         });
                //     } else {
                //         isChecked = false;
                //         checkResult.push({
                //             key: tempKey,
                //             value: false
                //         });
                //     }
                // }
                // results = results.concat(['<b>' + (tip ? tip : title) + `<br /></b>
                //     ${this.createShowHtml('checkbox', key, checkResult, configValue.map(item => {
                //     return {
                //         key: item,
                //         text: item,
                //         link: link
                //     }
                // }))}
                // `]);
                // if (!isChecked) {
                //     flowData.return = true;
                //     break;
                // }
            } else if (config.type == 'for-flow') {
                // 获取值，然后根据，分割，然后for循环
                const valueFromKey = (parentKey && parentKey.trim() != '') ? (parentKey + '_' + config.valueFrom) : config.valueFrom;
                const value = saveData[valueFromKey];
                const configValue = config.configValue;
                const list = value.split(/,|，/).map(item => item.trim()).filter(item => item.trim());
                results = results.concat([this.createShowHtml('radio', key, saveData[key], list.map(item => {
                    return {
                        key: item,
                        text: item
                    }
                }))]);
                let keyValue = saveData[key];
                let isComplete = true;
                if (!keyValue) {
                    // 找到当前循环到哪一个了
                    for (var f = 0; f < list.length; f++) {
                        const tempKey = list[f];
                        const lastChildrenKey = `${key}_${tempKey}_${configValue[configValue.length - 1].key}`;
                        if (!saveData[lastChildrenKey]) {
                            isComplete = false;
                            keyValue = tempKey;
                            break;
                        }
                    }
                }
                for (var f = 0; f < list.length; f++) {
                    const tempKey = list[f];
                    const lastChildrenKey = `${key}_${tempKey}_${configValue[configValue.length - 1].key}`;
                    if (!saveData[lastChildrenKey]) {
                        isComplete = false;
                    }
                    if (keyValue == tempKey) {
                        const childResults = this.printConfig(configValue.map(item => {
                            return {
                                ...item,
                                title: `${tempKey}: ${item.title}`
                            };
                        }), saveData, [], `${key}_${tempKey}`, tempKey);
                        results = results.concat(childResults.listData);
                        break;
                    }
                }
                if (!isComplete) {
                    flowData.return = true;
                    break;
                }
            } else if (!saveData[key] || (saveData[key] instanceof Array && saveData[key].length == 0)) {
                if (/发誓/.test(config.title)) {
                    config.configValue = config.configValue ? config.configValue : {
                        defaultValue: '我知道了'
                    }
                }
                flowData.return = true;
                results = results.concat(<Form.Item key={key} className={[styles.formItem, config.type].join(' ')} labelTextAlign={'left'} label={<h4 className={styles.title} dangerouslySetInnerHTML={{ __html: tip ? tip : title }} ></h4>}>
                    {this.createShowHtml(config.type, key, (config.defaultValue && !parentFlowKey) ? config.defaultValue : undefined, config.configValue)}
                </Form.Item>);
                break;
            } else {
                results = results.concat(<Form.Item className={[styles.formItem, config.type].join(' ')} key={key} labelTextAlign={'left'} label={<h4 className={styles.title} dangerouslySetInnerHTML={{ __html: title }} ></h4>}>
                    {this.createShowHtml(config.type, key, createFunc(saveData[key]), config.configValue)}
                </Form.Item>);
                if (config.type == 'radio') {
                    const prevValue = saveData[key];
                    const childResults = this.printConfig(config.children[prevValue], saveData, [], `${key}_${prevValue}`);
                    results = results.concat(childResults.listData);
                    if (childResults.flowData.return) {
                        flowData.return = true;
                        break;
                    }
                    if (childResults.flowData.continue) {
                        break;
                    }
                }
            }
        }
        return {
            listData: defaults.concat(results),
            flowData: flowData
        };
    }
    print() {
        // 1. 计划是为了上限，而非下限
        const configs = this.props.config;
        const saveData = this.state.data;
        let parentKey = '';
        const results: any = this.printConfig(configs, saveData, [], parentKey);
        return results.listData;
    }
    state = {
        data: {}
    }
    radioChange() {
        let saveData = {
            ...this.state.data,
            ...this.field.getValues()
        };
        this.field.setValues(saveData);
        this.setState({
            data: saveData
        });
        this.project.updateFileContent(this.props.filename, saveData).then(() => { });
    }
    componentDidMount(): void {
        this.project.getFileContent(this.props.filename).then(data => {
            if (data) {
                this.field.setValues(data);
                this.setState({ data });
            }
        });
        document.documentElement.addEventListener('keydown', (e) => {
            if (e.keyCode == 83 && (e.metaKey || e.ctrlKey)) {
                e.preventDefault();
                e.stopPropagation();
                let saveData = {
                    ...this.state.data,
                    ...this.field.getValues()
                };
                this.setState({
                    data: saveData
                });
                this.project.updateFileContent(this.props.filename, saveData);
            }
        });
    }
    render(): React.ReactNode {
        let data = this.print();
        return (
            <Form field={this.field}>
                {data}
            </Form>
        );
    }
};
